package com.cskaoyan.order.mq;

import com.cskaoyan.order.constant.OrderConstants;
import com.cskaoyan.order.dal.entitys.Order;
import com.cskaoyan.order.dal.entitys.Stock;
import com.cskaoyan.order.dal.persistence.OrderItemMapper;
import com.cskaoyan.order.dal.persistence.OrderMapper;
import com.cskaoyan.order.dal.persistence.StockMapper;
import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.client.exception.MQClientException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.nio.charset.StandardCharsets;
import java.util.Date;

/**
 * @author raccoon@littleraccoon.xyz
 * @since 2022/12/06 15:40
 */
@Component
public class DelayOrderCancelConsumer {
    DefaultMQPushConsumer defaultMQPushConsumer;

    @Autowired
    OrderMapper orderMapper;
    @Autowired
    OrderItemMapper orderItemMapper;
    @Autowired
    StockMapper stockMapper;

    @PostConstruct
    public void start() {
        defaultMQPushConsumer = new DefaultMQPushConsumer("delay_order_cancel_consumer");
        defaultMQPushConsumer.setNamesrvAddr("127.0.0.1:9876");
        defaultMQPushConsumer.setMessageListener((MessageListenerConcurrently) (list, consumeConcurrentlyContext) -> {
            byte[] body = list.get(0).getBody();
            String orderId = new String(body, 0, body.length, StandardCharsets.UTF_8);
            Order order = orderMapper.selectByPrimaryKey(orderId);
            if (order.getStatus() == OrderConstants.ORDER_STATUS_INIT) {
                // cancel
                order.setStatus(OrderConstants.ORDER_STATUS_TRANSACTION_CANCEL);
                orderItemMapper.queryByOrderId(orderId).forEach(x -> {
                    stockMapper.updateStock(Stock.builder()
                            .itemId(x.getItemId()).stockCount((long) x.getNum()).lockCount(~x.getNum() + 1)
                            .build());
                    orderItemMapper.updateStockStatus(OrderConstants.STOCK_RELEASED, orderId);
                });
                order.setUpdateTime(new Date());
                orderMapper.updateByPrimaryKeySelective(order);
            }
            return null;
        });
        try {
            defaultMQPushConsumer.subscribe("delay_order_cancel", "*");
            defaultMQPushConsumer.start();
        } catch (MQClientException e) {
            e.printStackTrace();
        }
    }
}
